package com.bq.gametrade.ui.fragment;

import android.content.Intent;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;

import com.bq.gametrade.HttpLink;
import com.bq.gametrade.R;
import com.bq.gametrade.adapter.TradingRecordsAdapter;
import com.bq.gametrade.base.BaseFragment;
import com.bq.gametrade.bean.UserTradingRecord;
import com.bq.gametrade.bean.UserTradingRecordDetails;
import com.bq.gametrade.http.VRHttp;
import com.bq.gametrade.http.VRHttpListener;
import com.bq.gametrade.ui.activity.LoginActivity;
import com.bq.gametrade.ui.activity.MainActivity;
import com.bq.gametrade.ui.activity.TradingRecordsDetailsActivity;
import com.bq.gametrade.ui.dialog.CustomPickDateDialog;
import com.bq.gametrade.ui.dialog.CustomerServiceDialog;
import com.bq.gametrade.utils.DateUtils;
import com.bq.gametrade.utils.NetworkUtils;
import com.bq.gametrade.utils.ToastUtils;
import com.bq.gametrade.view.pullableview.PullToRefreshLayout;
import com.bq.gametrade.view.pullableview.PullableListView;

import java.util.ArrayList;
import java.util.Collection;
import java.util.Collections;
import java.util.Comparator;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;

/**
 * @author Feel on 2016/11/24 15:28
 */

public class TradingFragment extends BaseFragment implements View.OnClickListener {

    private MainActivity activity;
    private ImageView ivService;

    private PullableListView listView;
    private PullToRefreshLayout refreshLayout;

    private TradingRecordsAdapter adapter;

    private TextView tvStartTime, tvEndTime;
    private Button toQuery;
    private TextView tvPormpt;
    private LinearLayout layPrompt;

    private ArrayList<UserTradingRecordDetails> mList = new ArrayList<>();

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        activity = (MainActivity) getActivity();
    }

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
        View root = inflater.inflate(R.layout.fragment_trading, container, false);
        initView(root);
        return root;
    }


    private void initView(View view) {
        ivService = (ImageView) view.findViewById(R.id.iv_userService);
        ivService.setOnClickListener(this);
        tvStartTime = (TextView) view.findViewById(R.id.tv_startTime);
        tvStartTime.setText(DateUtils.getLastWeakDate());
        tvStartTime.setOnClickListener(this);
        tvEndTime = (TextView) view.findViewById(R.id.tv_endTime);
        tvEndTime.setText(DateUtils.getDate());
        tvEndTime.setOnClickListener(this);
        toQuery = (Button) view.findViewById(R.id.btn_toQuery);
        toQuery.setOnClickListener(this);
        tvPormpt = (TextView) view.findViewById(R.id.tv_pormpt);
        listView = (PullableListView) view.findViewById(R.id.lisView_trading);
        listView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> adapterView, View view, int i, long l) {
                Intent intent = new Intent(getActivity(), TradingRecordsDetailsActivity.class);
                intent.putExtra("tradingRecordId",mList.get(i).orderId);
                intent.putExtra("tradingType",mList.get(i).order_type);
                startActivity(intent);
            }
        });
        refreshLayout = (PullToRefreshLayout) view.findViewById(R.id.layout_refresh);
        layPrompt = (LinearLayout) view.findViewById(R.id.lay_prompt);
        initListView();

    }

    @Override
    public void setUserVisibleHint(boolean isVisibleToUser) {
        super.setUserVisibleHint(isVisibleToUser);
        if (isVisibleToUser && isVisible()) {
            if (application.isLogin()) {
                getTradingRecord(DateUtils.getLastWeakDate(), DateUtils.getDate());
            } else {
                mList.clear();
                tvPormpt.setText("您还没有登陆哦！");
                tvPormpt.setVisibility(View.VISIBLE);
                layPrompt.setVisibility(View.VISIBLE);
            }
        }
    }

    private void initListView() {
        adapter = new TradingRecordsAdapter(activity, mList);

        listView.setAdapter(adapter);
        refreshLayout.setOnRefreshListener(new PullToRefreshLayout.OnRefreshListener() {
            @Override
            public void onRefresh(final PullToRefreshLayout pullToRefreshLayout) {

                if (!application.isLogin()) {
                    pullToRefreshLayout.loadmoreFinish(PullToRefreshLayout.FAIL);
                    ToastUtils.showToast(activity, "您还没有登陆");
                    return;
                }
                getTradingRecordRefresh(DateUtils.getLastWeakDate(), DateUtils.getDate(), pullToRefreshLayout);

            }

            @Override
            public void onLoadMore(final PullToRefreshLayout pullToRefreshLayout) {
                // 加载操作
                new Handler() {
                    @Override
                    public void handleMessage(Message msg) {
                        // 千万别忘了告诉控件加载完毕了哦！

                        ToastUtils.showToast(getActivity(), "没有更多数据了");
                        pullToRefreshLayout.loadmoreFinish(PullToRefreshLayout.SUCCEED);
                    }
                }.sendEmptyMessageDelayed(0, 3000);
            }
        });
    }

    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.iv_userService:
                CustomerServiceDialog dialog = new CustomerServiceDialog();
                dialog.show(getFragmentManager(), "show");
                break;
            case R.id.tv_startTime:
                CustomPickDateDialog dateDialog = new CustomPickDateDialog(activity,
                        DateUtils.formatDateChinese(new Date()));
                dateDialog.dateTimePicKDialog(tvStartTime);
                break;
            case R.id.tv_endTime:
                CustomPickDateDialog myDateDialog = new CustomPickDateDialog(activity,
                        DateUtils.formatDateChinese(new Date()));
                myDateDialog.dateTimePicKDialog(tvEndTime);
                break;
            case R.id.btn_toQuery:
                if (!application.isLogin()) {
                    ToastUtils.showToast(activity, "您还没有登陆");
                    return;
                }
                if (tvStartTime.getText().toString().equals("起始时间")) {
                    ToastUtils.showToast(activity, "起始时间未输入");
                    return;
                }
                if (tvEndTime.getText().toString().equals("结束时间")) {
                    ToastUtils.showToast(activity, "结束时间未输入");
                    return;
                }
                if (DateUtils.compareDate(tvStartTime.getText().toString(), tvEndTime.getText().toString()) == -1) {
                    ToastUtils.showToast(activity, "结束时间不能小于起始时间");
                    return;
                }
                if (NetworkUtils.isNetworkAvailable(activity)) {
                    getTradingRecord(tvStartTime.getText().toString(), tvEndTime.getText().toString());

                } else {
                    ToastUtils.showToast(activity, "没有网络了····");
                }

                break;
        }
    }

    private void getTradingRecord(String startDate, String endDate) {
        Map<String, String> params = new HashMap<>();
        params.put("token", application.getUserInfo().token);
        params.put("start", startDate);
        params.put("end", endDate);
        showSpotsDialog();
        VRHttp.getTradingRecordList(getActivity(), HttpLink.USER_TRADINGRECORD_URL, params, new VRHttpListener() {
            @Override
            public void onSuccess(Object response, boolean isCache) {
                if (response != null) {
                    UserTradingRecord userTradingRecord = (UserTradingRecord)response;
                    if (userTradingRecord.status.equals("0")) {
                        mList = userTradingRecord.record_list;
                        if (mList.size() > 0) {
                            Collections.sort(mList, new Comparator<UserTradingRecordDetails>() {
                                @Override
                                public int compare(UserTradingRecordDetails lhs, UserTradingRecordDetails rhs) {
                                    Date date1 = DateUtils.stringToDate(lhs.ctime);
                                    Date date2 = DateUtils.stringToDate(rhs.ctime);
                                    // 对日期字段进行升序，如果欲降序可采用after方法
                                    if (date1.before(date2)) {
                                        return 1;
                                    }
                                    return -1;
                                }
                            });
                            adapter.setData(mList);
                            adapter.notifyDataSetChanged();
                            layPrompt.setVisibility(View.GONE);
                            refreshLayout.loadmoreFinish(PullToRefreshLayout.SUCCEED);
                        }else {
                            layPrompt.setVisibility(View.VISIBLE);
                            tvPormpt.setVisibility(View.VISIBLE);
                            tvPormpt.setText("您还没有交易记录哦!");

                        }
                    } else if (userTradingRecord.status.equals("99")) {
                        ToastUtils.showToast(getActivity(), "登录超时，重新登录");
                        application.setUserInfo(null);
                        startActivity(new Intent(getActivity(), LoginActivity.class));
                    }
                    else if (userTradingRecord.status.equals("98")) {
                        ToastUtils.showToast(getActivity(), "您的账号已在其他设备登录，如果不人本人登录请及时修改密码");
                        application.setUserInfo(null);
                        startActivity(new Intent(getActivity(), LoginActivity.class));
                    }
                } else {
                    ToastUtils.showToast(getActivity(), "您还没有交易记录");
                }
            }

            @Override
            public void onFinish() {
                super.onFinish();
                closeSpotsDialog();
            }

            @Override
            public void onError(String error) {
                super.onError(error);
                ToastUtils.showToast(getActivity(), "获取数据出错");
            }
        });
    }

    private void getTradingRecordRefresh(String startDate, String endDate, final PullToRefreshLayout refreshLayout) {
//        if(tvStartTime.getText().toString() !=null && tvEndTime.getText().toString() != null){
//            startDate = tvStartTime.getText().toString();
//            endDate = tvEndTime.getText().toString();
//        }
        Map<String, String> params = new HashMap<>();
        params.put("token", application.getUserInfo().token);
        params.put("start", startDate);
        params.put("end", endDate);
        VRHttp.getTradingRecordList(getActivity(), HttpLink.USER_TRADINGRECORD_URL, params, new VRHttpListener() {
            @Override
            public void onSuccess(Object response, boolean isCache) {
                if (response != null) {
                    refreshLayout.loadmoreFinish(PullToRefreshLayout.SUCCEED);
                    UserTradingRecord userTradingRecord = (UserTradingRecord) response;
                    if (userTradingRecord.status.equals("0")) {
                        mList = userTradingRecord.record_list;
                        if (mList.size() > 0) {
                            Collections.sort(mList, new Comparator<UserTradingRecordDetails>() {
                                @Override
                                public int compare(UserTradingRecordDetails lhs, UserTradingRecordDetails rhs) {
                                    Date date1 = DateUtils.stringToDate(lhs.ctime);
                                    Date date2 = DateUtils.stringToDate(rhs.ctime);
                                    // 对日期字段进行升序，如果欲降序可采用after方法
                                    if (date1.before(date2)) {
                                        return 1;
                                    }
                                    return -1;
                                }
                            });
                            adapter.setData(mList);
                            adapter.notifyDataSetChanged();
                            layPrompt.setVisibility(View.GONE);
                            refreshLayout.loadmoreFinish(PullToRefreshLayout.SUCCEED);
                        }else {
                            layPrompt.setVisibility(View.VISIBLE);
                            tvPormpt.setVisibility(View.VISIBLE);
                            tvPormpt.setText("您还没有交易记录哦!");

                        }
                    } else if (userTradingRecord.status.equals("99")) {
                        ToastUtils.showToast(getActivity(), "登录超时，重新登录");
                        application.setUserInfo(null);
                        startActivity(new Intent(getActivity(), LoginActivity.class));
                    }

                } else {
                    ToastUtils.showToast(getActivity(), "您还没有交易记录");
                }
            }

            @Override
            public void onFinish() {
                super.onFinish();
            }

            @Override
            public void onError(String error) {
                super.onError(error);
                refreshLayout.loadmoreFinish(PullToRefreshLayout.FAIL);
                ToastUtils.showToast(getActivity(), "获取数据出错");
            }
        });
    }
}
